package controller

import (
	"net/http"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"

	"gitee.com/wangshh_123/cross-pay-go/src/service"
	"gitee.com/wangshh_123/cross-pay-go/src/utils/common"
)

// CardBalanceSyncController 卡片余额同步控制器
type CardBalanceSyncController struct {
	cardBalanceSyncService *service.CardBalanceSyncService
}

// NewCardBalanceSyncController 创建卡片余额同步控制器
func NewCardBalanceSyncController(db *gorm.DB) *CardBalanceSyncController {
	return &CardBalanceSyncController{
		cardBalanceSyncService: service.NewCardBalanceSyncService(db),
	}
}

// SyncCardBalanceFromAPI 从API同步卡片余额
func (c *CardBalanceSyncController) SyncCardBalanceFromAPI(ctx *gin.Context) {
	userID := ctx.GetInt64("user_id")
	platform := ctx.Query("platform")

	if platform == "" {
		common.Error(ctx, http.StatusBadRequest, "platform parameter is required", nil)
		return
	}

	if err := c.cardBalanceSyncService.SyncCardBalanceFromAPI(ctx, userID, platform); err != nil {
		common.Error(ctx, http.StatusInternalServerError, "Failed to sync card balance: "+err.Error(), err)
		return
	}

	common.Success(ctx, gin.H{
		"message":  "Card balance sync completed",
		"userID":   userID,
		"platform": platform,
	})
}

// SyncCardBalanceFromCardListAPI 从卡片列表API响应同步余额
func (c *CardBalanceSyncController) SyncCardBalanceFromCardListAPI(ctx *gin.Context) {
	userID := ctx.GetInt64("user_id")
	platform := ctx.Query("platform")

	if platform == "" {
		common.Error(ctx, http.StatusBadRequest, "platform parameter is required", nil)
		return
	}

	// 从请求体中获取API响应数据
	var apiResponse map[string]interface{}
	if err := ctx.ShouldBindJSON(&apiResponse); err != nil {
		common.Error(ctx, http.StatusBadRequest, "Invalid request body: "+err.Error(), err)
		return
	}

	if err := c.cardBalanceSyncService.SyncCardBalanceFromCardListAPI(ctx, userID, platform, apiResponse); err != nil {
		common.Error(ctx, http.StatusInternalServerError, "Failed to sync card balance from API response: "+err.Error(), err)
		return
	}

	common.Success(ctx, gin.H{
		"message":  "Card balance sync from API response completed",
		"userID":   userID,
		"platform": platform,
	})
}

// GetCardBalanceSummary 获取卡片余额统计
func (c *CardBalanceSyncController) GetCardBalanceSummary(ctx *gin.Context) {
	userID := ctx.GetInt64("user_id")

	summary, err := c.cardBalanceSyncService.GetCardBalanceSummary(ctx, userID)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "Failed to get card balance summary: "+err.Error(), err)
		return
	}

	common.Success(ctx, summary)
}

// ListCardsWithZeroBalance 列出余额为0的卡片
func (c *CardBalanceSyncController) ListCardsWithZeroBalance(ctx *gin.Context) {
	userID := ctx.GetInt64("user_id")
	platform := ctx.Query("platform")

	var cards []map[string]interface{}
	query := c.cardBalanceSyncService.GetDB().Table("user_cards").
		Where("user_id = ? AND TotalTransferAmount = ?", userID, 0)

	if platform != "" {
		query = query.Where("platform = ?", platform)
	}

	if err := query.Find(&cards).Error; err != nil {
		common.Error(ctx, http.StatusInternalServerError, "Failed to get cards with zero balance: "+err.Error(), err)
		return
	}

	common.Success(ctx, gin.H{
		"cards":    cards,
		"count":    len(cards),
		"userID":   userID,
		"platform": platform,
	})
}

// ListCardsByPlatform 按平台列出卡片
func (c *CardBalanceSyncController) ListCardsByPlatform(ctx *gin.Context) {
	userID := ctx.GetInt64("user_id")
	platform := ctx.Query("platform")

	if platform == "" {
		common.Error(ctx, http.StatusBadRequest, "platform parameter is required", nil)
		return
	}

	var cards []map[string]interface{}
	if err := c.cardBalanceSyncService.GetDB().Table("user_cards").
		Where("user_id = ? AND platform = ?", userID, platform).
		Find(&cards).Error; err != nil {
		common.Error(ctx, http.StatusInternalServerError, "Failed to get cards by platform: "+err.Error(), err)
		return
	}

	common.Success(ctx, gin.H{
		"cards":    cards,
		"count":    len(cards),
		"userID":   userID,
		"platform": platform,
	})
}

// ManualSyncCardBalance 手动同步指定卡片的余额
func (c *CardBalanceSyncController) ManualSyncCardBalance(ctx *gin.Context) {
	userID := ctx.GetInt64("user_id")

	var req struct {
		CardID   string `json:"cardId" binding:"required"`
		Balance  string `json:"balance" binding:"required"`
		Platform string `json:"platform" binding:"required"`
	}

	if err := ctx.ShouldBindJSON(&req); err != nil {
		common.Error(ctx, http.StatusBadRequest, "Invalid request body: "+err.Error(), err)
		return
	}

	// 更新指定卡片的余额
	if err := c.cardBalanceSyncService.GetDB().Model(&struct{}{}).
		Table("user_cards").
		Where("card_id = ? AND user_id = ?", req.CardID, userID).
		Update("TotalTransferAmount", req.Balance).Error; err != nil {
		common.Error(ctx, http.StatusInternalServerError, "Failed to update card balance: "+err.Error(), err)
		return
	}

	common.Success(ctx, gin.H{
		"message":  "Card balance updated successfully",
		"cardId":   req.CardID,
		"balance":  req.Balance,
		"platform": req.Platform,
	})
}
